package com.example.a10928.weifriend.http.configuration;

import com.google.gson.Gson;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * Created by Chuang on 2018/2/26.
 * 把继承自{@link Params}的请求参数转换成json;
 */

public class GsonParamsConverterFactory extends Converter.Factory {
    private Gson mGson;

    private GsonParamsConverterFactory(Gson gson) {
        mGson = gson;
    }

    public static GsonParamsConverterFactory create(Gson gson) {
        return new GsonParamsConverterFactory(gson);
    }

    @Override
    public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        if (type instanceof Class) {
            if (Params.class.isAssignableFrom((Class<?>) type))
                return new GsonParamsConverter(mGson, type);
        }
        return null;
    }

    private static class GsonParamsConverter implements Converter<Params, String> {

        private final Type mType;
        private Gson mGson;

        private GsonParamsConverter(Gson gson, Type type) {
            mGson = gson;
            mType = type;
        }

        @Override
        public String convert(Params value) throws IOException {
            return mGson.toJson(value, mType);
        }
    }
}

